<template>
  <div class="search-wrap">
    <input v-model="keyword" class="header-input" type="search" placeholder="输入城市名或拼音">
    <div class="search-content"  v-show="keyword" ref="search">
      <ul>
        <li v-for="item in list" :key="item.id" @click='handleChangeCity(item.name)'>{{item.name}}</li>
        <li v-if="showsearchcity">WDNMD</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'search',
  props: {
    cities: Object
  },
  data () {
    return {
      timer: null,
      keyword: '',
      list: []
    }
  },
  methods: {
    handleChangeCity (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    showsearchcity () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = ''
        return this.list
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  updated () {
    this.scroll = new BScroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
   @import '~styles/varibles.styl'
  .search-wrap
    background-color $bgColor
    height: .66rem;
    padding: .1rem;
    .header-input
      flex:1;
      height: .64rem;
      width: 100%
      text-align: center;;
      line-height: .64rem;
      padding-left: .2rem;
      font-weight: 550
      background-color: #fff;
      color: #333;
      border-radius :.1rem;
    .search-content
      position: absolute;
      overflow: hidden;
      top: 1.7rem;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #fff;
      z-index:1;
      li
        line-height: .8rem;
        padding-left: .1rem;
        border-bottom: 0.02rem solid #eee
</style>
